package flc.ast.dataBase;

import android.content.Context;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

import flc.ast.bean.Album;
import flc.ast.bean.AlbumBean;
import flc.ast.bean.Image;
import flc.ast.bean.PictureClsBean;

public class AlbumRepository {
    private final AlbumDao albumDao;

    public AlbumRepository(Context context) {
        albumDao = AppDatabase.getInstance(context).albumDao();
    }


    //获取所有相册及其包含的图片
    public List<AlbumBean> getAllAlbumsWithImages() {
        List<AlbumBean> albums = new ArrayList<>();
        for (Album album : albumDao.getAllAlbums()) {
            AlbumBean albumBean = new AlbumBean();
            albumBean.setAlbum(album);
            albumBean.setImages(albumDao.getImagesByAlbumId(album.id));
            albums.add(albumBean);
        }
        return albums;
    }

    // 获取按标签分类的Map（按标签名升序）
    public List<PictureClsBean> getImagesGroupedByTag() {
        List<Image> images = albumDao.getAllImages();
        Map<String, List<Image>> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

        for (Image image : images) {
            if (image.tags != null) {
//                String[] tags = image.tags.split(",");
//                for (String tag : tags) {
//                    tag = tag.trim();
//                    if (!result.containsKey(tag)) {
//                        result.put(tag, new ArrayList<>());
//                    }
//                    result.get(tag).add(image);
//                }
                String tag = image.tags.trim();
                if (!result.containsKey(tag)) {
                    result.put(tag, new ArrayList<>());
                }
                result.get(tag).add(image);
            }
        }
        List<PictureClsBean> pictureClsBeanList = new ArrayList<>();
        Iterator<String> iterator = result.keySet().iterator();
        String title = null;
        while (iterator.hasNext()) {
            title = iterator.next();
            pictureClsBeanList.add(new PictureClsBean(title, result.get(title)));
        }
        return pictureClsBeanList;
    }

    // 获取按城市分类的Map（按城市名升序）
    public List<PictureClsBean> getImagesGroupedByCity() {
        Map<String, List<Image>> map = albumDao.getAllImages().stream()
                .filter(img -> img.city != null)
                .collect(Collectors.groupingBy(
                        img -> img.city.trim(),
                        () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER), // 不区分大小写的字母序
                        Collectors.toList()
                ));
        List<PictureClsBean> pictureClsBeanList = new ArrayList<>();
        Iterator<String> iterator = map.keySet().iterator();
        String title = null;
        while (iterator.hasNext()) {
            title = iterator.next();
            pictureClsBeanList.add(new PictureClsBean(title, map.get(title)));
        }
        return pictureClsBeanList;
    }


    // 获取按日期分类的Map（按时间降序）
    public List<PictureClsBean> getImagesGroupedByDate() {
        List<Image> images = albumDao.getAllImages();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

        // 创建按日期字符串降序排序的TreeMap
        Comparator<String> dateComparator = (date1, date2) -> {
            try {
                Date d1 = sdf.parse(date1);
                Date d2 = sdf.parse(date2);
                return d2.compareTo(d1); // 降序排序
            } catch (ParseException e) {
                return 0; // 如果解析失败，保持原顺序
            }
        };

        Map<String, List<Image>> map = images.stream()
                .sorted(Comparator.comparing(Image::getTime).reversed())
                .collect(Collectors.groupingBy(
                        img -> sdf.format(new Date(img.time)),
                        () -> new TreeMap<>(dateComparator),
                        Collectors.toList()
                ));

        return mapToList(map);
    }

    // 按日期范围筛选图片（结果按时间降序）
    public List<PictureClsBean> getImagesGroupedByDateRange(long selime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

        // 创建日期降序比较器
        Comparator<String> dateDescComparator = (date1, date2) -> {
            try {
                Date d1 = sdf.parse(date1);
                Date d2 = sdf.parse(date2);
                return d2.compareTo(d1); // 降序排序
            } catch (ParseException e) {
                return 0;
            }
        };

        Map<String, List<Image>> map = albumDao.getAllImages().stream()
                .filter(img -> sdf.format(new Date(img.time)).equals(sdf.format(new Date(selime))))
                .sorted(Comparator.comparing(Image::getTime).reversed())
                .collect(Collectors.groupingBy(
                        img -> sdf.format(new Date(img.time)),
                        () -> new TreeMap<>(dateDescComparator),
                        Collectors.toList()
                ));

        return mapToList(map);
    }

    // 按标签筛选图片（结果按时间降序）
    public List<PictureClsBean> getImagesByTag(String tag) {
        List<Image> imageList = albumDao.getAllImages().stream()
                .filter(img -> img.tags != null &&
                        Arrays.asList(img.tags.split(","))
                                .stream()
                                .anyMatch(t -> t.trim().equalsIgnoreCase(tag)))
                .sorted(Comparator.comparing(Image::getTime).reversed())
                .collect(Collectors.toList());
        List<PictureClsBean> pictureClsBeanList = new ArrayList<>();
        pictureClsBeanList.add(new PictureClsBean(tag, imageList));
        return pictureClsBeanList;
    }

    // 按城市筛选图片（结果按时间降序）
    public List<PictureClsBean> getImagesByCity(String city) {
        List<Image> imageList = albumDao.getAllImages().stream()
                .filter(img -> img.city != null &&
                        img.city.toLowerCase().equals(city == null ? "" : city.toLowerCase()))
                .sorted(Comparator.comparing(Image::getTime).reversed())
                .collect(Collectors.toList());
        List<PictureClsBean> pictureClsBeanList = new ArrayList<>();
        pictureClsBeanList.add(new PictureClsBean(city, imageList));
        return pictureClsBeanList;
    }

    private List<PictureClsBean> mapToList(Map<String, List<Image>> map) {
        List<PictureClsBean> pictureClsBeanList = new ArrayList<>();
        Iterator<String> iterator = map.keySet().iterator();
        String title = null;
        while (iterator.hasNext()) {
            title = iterator.next();
            pictureClsBeanList.add(new PictureClsBean(title, map.get(title)));
        }
        return pictureClsBeanList;
    }

}
